<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import * as echarts from 'echarts'
import type { WarningExecutionLog } from '@/models/warning'

interface Props {
  logs: WarningExecutionLog[]
}

const emit = defineEmits<{
  (e: 'pointClick', id: string): void
}>()

const props = defineProps<Props>()
const chartRef = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

onMounted(() => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    updateChart()
    setupChartEvents()
  }
})

watch(
  () => props.logs,
  () => {
    updateChart()
    setupChartEvents()
  },
  { deep: true }
)

function setupChartEvents() {
  if (!chartInstance) return

  chartInstance.off('click')
  chartInstance.on('click', (params: any) => {
    if (params.componentType === 'series') {
      const configId = params.seriesName
      const timestamp = params.value[0]
      const log = props.logs.find(
        log =>
          log.configId === configId &&
          new Date(log.startTime).getTime() === timestamp
      )
      if (log) {
        emit('pointClick', log.id)
      }
    }
  })
}

function updateChart() {
  if (!chartInstance || !props.logs?.length) return

  // 按configId分组数据
  const configGroups: Record<string, WarningExecutionLog[]> = {}
  props.logs.forEach(log => {
    if (!configGroups[log.configId]) {
      configGroups[log.configId] = []
    }
    configGroups[log.configId].push(log)
  })

  // 准备series数据
  const series = Object.entries(configGroups).map(([configId, logs]) => {
    return {
      name: configId,
      type: 'line',
      data: logs.map(log => {
        const timestamp = new Date(log.startTime).getTime()
        return {
          name: timestamp,
          value: [timestamp, log.matchedCount],
        }
      }),
      symbolSize: 8,
      showSymbol: true,
      smooth: true,
    }
  })

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const date = new Date(params[0].value[0])
        return `
          <div>配置ID: ${params[0].seriesName}</div>
          <div>时间: ${date.toLocaleString()}</div>
          <div>匹配数量: ${params[0].value[1]}</div>
        `
      },
    },
    legend: {
      data: Object.keys(configGroups),
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'time',
      axisLabel: {
        formatter: (value: number) => {
          return new Date(value).toLocaleTimeString()
        },
      },
    },
    yAxis: {
      type: 'value',
      name: '匹配数量',
    },
    series,
  }

  chartInstance.setOption(option)
  chartInstance.resize()
}
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 400px"></div>
</template>
